<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="846px"
      :title="parameter.text"
      wrapClassName="add-modal-container"
      @cancel="closeModal()"
    >
      <div class="curve-modal-body">
        <a-form-model ref="ruleForm" :model="form" :rules="rules">
          <a-row :gutter="0">
            <a-col :span="12">
              <a-form-model-item
                label="专家姓名"
                prop="userUuid"
                :rules="{
                  required: true,
                  message: '请选择专家',
                }"
              >
                <bjSelectPopup
                  placeholder="请选择专家"
                  v-model="form.userUuid"
                  url="/mdata/user/getPageSet"
                  @cancel="cancel"
                  @ok="ok"
                  @close="popupClose"
                >
                </bjSelectPopup>
                <!-- <a-select
                  showSearch
                  :filter-option="filterOption"
                  placeholder="请选择专家"
                  v-model="form.expertName"
                  :loading="expertLoading"
                  @change="expertChange($event)"
                >
                  <a-select-option
                    :value="item.userNameId"
                    v-for="item in expertSource"
                    :key="item.uuid"
                  >
                    {{ item.userName }}
                  </a-select-option>
                </a-select> -->
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="性别">
                <a-select v-model="form.sex" disabled>
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in sexSource"
                    :key="item.uuid"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="12">
              <a-form-model-item label="身份证号">
                <a-input
                  v-model.trim="form.idCard"
                  @blur="idNumberBlur()"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="联系方式">
                <a-input v-model.trim="form.mobile" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="12">
              <a-form-model-item label="出生年月">
                <a-date-picker
                  disabled
                  style="width: 100%"
                  v-model="form.birthDate"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  placeholder=" "
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="籍贯" prop="nativePlace">
                <a-cascader
                  v-model="nativePlace"
                  :options="areaData"
                  placeholder="请选择籍贯"
                  :fieldNames="{
                    label: 'name',
                    value: 'name',
                    children: 'children',
                  }"
                  @change="changeNativePlace($event)"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="12">
              <a-form-model-item label="职称" prop="technicalTitle">
                <a-select
                  placeholder="请选择职称"
                  v-model="form.technicalTitle"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in technicalSource"
                    :key="item.uuid"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item
                label="专业"
                prop="zySelect"
                :rules="{
                  required: true,
                  validator: validateMajor,
                }"
              >
                <a-select
                  :maxTagCount="2"
                  v-model="form.zySelect"
                  mode="tags"
                  placeholder="请选择专业"
                  @change="zyChange($event)"
                >
                  <a-select-option v-for="v in majorSource" :key="v.uuid">
                    {{ v.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="12">
              <a-form-model-item label="入库时间" prop="enterTime">
                <a-date-picker
                  style="width: 100%"
                  v-model="form.enterTime"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  placeholder="请选择入库时间"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div class="curve-modal-footer">
        <a-button type="default" @click="closeModal()">取消 </a-button>
        <a-button type="primary" @click="onSubmit()" :loading="buttonLoading">
          确定
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import moment from "moment";
import areaData from "@/components/_utils/area-json.js";
import { parseCardInfo, isCardID } from "@/utils/index.js";
import bjSelect from "@/components/extendCustom/bj-select";
import bjSelectPopup from "@/components/extendCustom/bj-select-popup";
import DepartPopup from "@/components/TopVUI/custom/DepartPopup";
import { axios } from "@/utils/request";
export default {
  name: "addModal",
  components: {
    bjSelect,
    DepartPopup,
    bjSelectPopup,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    parameter: {
      type: Object,
      default: {},
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          let { uuid } = this.parameter;
          this.getData();
          if (uuid) {
            this.getDetail();
          } else {
            this.form.enterTime = moment().format("YYYY-MM-DD");
          }
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      buttonLoading: false,
      form: {
        //专家姓名
        expertName: undefined,
        //身份证号
        idCard: "",
        //联系方式
        mobile: "",
        //专业
        professionType: undefined,
        professionName: "",
        //职称
        technicalTitle: undefined,
        technicalTitleName: "",
        //性别
        sex: undefined,
        //籍贯
        nativePlace: "",
        //出生年月
        birthDate: "",
        //入库时间
        enterTime: "",
        zySelect: [],
        userUuid: "",
      },
      rules: {
        technicalTitle: [
          { required: true, message: "请选择职称", trigger: "change" },
        ],
        nativePlace: [
          { required: true, message: "请选择籍贯", trigger: "change" },
        ],
        enterTime: [
          {
            required: true,
            message: "请选择入库时间",
            trigger: "change",
          },
        ],
      },
      //专业
      majorSource: [],
      majorLoading: false,
      checkList: [],
      //职称
      technicalSource: [],
      technicalLoading: false,
      //籍贯
      areaData: areaData,
      nativePlace: [],
      //性别
      sexLoading: false,
      sexSource: [],
      //专家下拉框
      expertLoading: false,
      expertSource: [],
    };
  },
  methods: {
    popupClose() {
      this.form.expertName = "";
      this.form.idCard = "";
      this.form.birthDate = "";
      this.form.mobile = "";
      this.form.sex = undefined;
      this.form.userUuid = "";
    },
    ok(ev) {
      let soucre = ev?.[0] ?? {};
      this.form.expertName = soucre.userName;
      this.form.idCard = soucre.idCard;
      this.form.birthDate = soucre.userBirthday;
      this.form.mobile = soucre.userCellphone;
      this.form.sex = soucre.userSex;
      this.form.userUuid = soucre.uuid;
    },
    cancel() {
      this.form.expertName = "";
      this.form.idCard = "";
      this.form.birthDate = "";
      this.form.mobile = "";
      this.form.sex = undefined;
      this.form.userUuid = "";
    },
    moment,
    //查询专家
    getExpertList() {
      this.expertLoading = true;
      return new Promise((resolve, reject) => {
        this.$post(`/mdata/user/getPageSet?pageNo=${1}&pageSize=${999}`, {})
          .then((res) => {
            let { data } = res;
            this.expertSource = data.rows || [];
            resolve();
          })
          .catch((_) => {
            this.expertSource = [];
            reject();
          })
          .finally((_) => {
            this.expertLoading = false;
          });
      });
    },
    expertChange(ev) {
      let soucre = this.expertSource.find((v) => v.userNameId == ev);
      this.form.idCard = soucre.idCard;
      this.form.birthDate = soucre.userBirthday;
      this.form.mobile = soucre.userCellphone;
      this.form.sex = soucre.userSex;
      this.form.userUuid = soucre.uuid;
    },

    //验证专业
    validateMajor(rule, value, callback) {
      let { zySelect = [] } = this.form;
      if (zySelect && zySelect.length == 0) {
        callback(new Error(`请选择专业`));
      } else {
        callback();
      }
    },
    //选择籍贯
    changeNativePlace(value) {
      this.form.nativePlace = value.join("/");
    },
    //根据身份证解析数据
    idNumberBlur() {
      let no = this.form.idCard;
      if (no && isCardID(no)) {
        this.form.birthDate = parseCardInfo(no, 1);
        this.form.sex = parseCardInfo(no, 2);
        this.nativePlace = parseCardInfo(no, 4).map((v) => v.name);
        this.form.nativePlace = this.nativePlace.join("/");
      }
    },
    //选择专业
    zyChange(e) {
      //页面回显强制更新
      this.$forceUpdate();
    },

    getData() {
      Promise.all([
        this.getExpertList(),
        this.getMajorList(),
        this.getTechnicalList(),
        this.getSexList(),
      ])
        .then()
        .finally((_) => {});
    },

    //查询专业
    getMajorList() {
      this.majorLoading = true;
      return new Promise((resolve, reject) => {
        this.$post("/system/dicSet/getDicItemByCode", {
          code: "professionType",
        })
          .then((res) => {
            let { data } = res;
            this.majorSource = data || [];
            resolve();
          })
          .catch((_) => {
            this.majorSource = [];
            reject();
          })
          .finally((_) => {
            this.majorLoading = false;
          });
      });
    },
    //查询职称
    getTechnicalList() {
      this.technicalLoading = true;
      return new Promise((resolve, reject) => {
        this.$post("/system/dicSet/getDicItemByCode", {
          code: "technicalTitle",
        })
          .then((res) => {
            let { data } = res;
            this.technicalSource = data || [];
            resolve();
          })
          .catch((_) => {
            this.technicalSource = [];
            reject();
          })
          .finally((_) => {
            this.technicalLoading = false;
          });
      });
    },
    //查询性别
    getSexList() {
      this.sexLoading = true;
      return new Promise((resolve, reject) => {
        this.$post("/system/dicSet/getDicItemByCode", {
          code: "UserSex",
        })
          .then((res) => {
            let { data } = res;
            this.sexSource = data || [];
            resolve();
          })
          .catch((_) => {
            this.sexSource = [];
            reject();
          })
          .finally((_) => {
            this.sexLoading = false;
          });
      });
    },

    //查询详情
    getDetail() {
      let { uuid } = this.parameter;
      axios
        .post(
          `/probusiness/configExpert/getDetailByUuid?varchar=${uuid}`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          this.form = {
            //专家姓名
            expertName: res.expertName,
            //身份证号
            idCard: res.idCard,
            //联系方式
            mobile: res.mobile,
            //专业
            professionType: res?.professionType || "",
            professionName: res.professionName,
            //职称
            technicalTitle: res.technicalTitle,
            technicalTitleName: res.technicalTitleName,
            //性别
            sex: res.sex,
            //籍贯
            nativePlace: res?.nativePlace || "",
            //出生年月
            birthDate: res.birthDate,
            //入库时间
            enterTime: res.enterTime,
            userUuid: res.userUuid,
          };
          // 籍贯
          this.nativePlace = this.form?.nativePlace.split("/") || [];
          //专业
          let list = this.form?.professionType.split(",") || [];
          this.form.zySelect = [];
          this.majorSource.forEach((item) => {
            list.forEach((v) => {
              if (item.dicItemCode == v) {
                this.form.zySelect.push(item.uuid);
              }
            });
          });
        })
        .catch((_) => {
          this.nativePlace = [];
        });
    },

    //提交
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          let { form, majorSource } = this;
          let { uuid } = this.parameter;
          //多选专业处理
          this.checkList = form.zySelect || [];
          let dic = [];
          let array = [];
          majorSource.forEach((item) => {
            this.checkList.forEach((v) => {
              if (item.uuid == v) {
                dic.push({
                  dicItemCode: item.dicItemCode,
                  dicItemName: item.dicItemName,
                });
                var _index = this.checkList.indexOf(v);
                array.push(this.checkList[_index]);
                this.checkList.splice(_index, 1);
              }
            });
          });
          this.form.zySelect = [...array, ...this.checkList];
          let value = dic.map((v) => v.dicItemCode);
          let formJson = {
            //专家姓名
            expertName: form.expertName,
            //身份证号
            idCard: form.idCard,
            //联系方式
            mobile: form.mobile,
            //专业
            professionType: value.toString(),
            //职称
            technicalTitle: form.technicalTitle,
            //性别
            sex: form.sex,
            //籍贯
            nativePlace: form.nativePlace,
            //出生年月
            birthDate: form.birthDate,
            //入库时间
            enterTime: form.enterTime,
            userUuid: form.userUuid,
          };
          let url = "";
          if (uuid) {
            formJson.uuid = uuid;
            url = "/probusiness/configExpert/update";
          } else {
            url = "/probusiness/configExpert/save";
          }
          axios
            .post(url, formJson, {
              headers: {
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success(
                  res.message ? res.message : "操作成功",
                  1.5
                );
                this.closeModal();
                this.$parent.getTableData();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.$refs["ruleForm"].clearValidate(["zySelect"]);
              this.buttonLoading = false;
            });
        }
      });
    },

    //关闭弹窗
    closeModal() {
      this.resetForm();
      this.nativePlace = [];
      this.$emit("update:visible", false);
    },
    //重置表单
    resetForm() {
      this.form.zySelect = [];
      this.checkList = [];
      this.form = {
        //专家姓名
        expertName: undefined,
        //身份证号
        idCard: "",
        //联系方式
        mobile: "",
        //专业
        professionType: undefined,
        professionName: "",
        //职称
        technicalTitle: undefined,
        technicalTitleName: "",
        //性别
        sex: undefined,
        //籍贯
        nativePlace: "",
        //出生年月
        birthDate: "",
        //入库时间
        enterTime: "",
        userUuid: "",
      };
      this.$refs.ruleForm.resetFields();
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: @primary-color;
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .ant-modal-header {
    position: relative;
    .ant-modal-title {
      &::before {
        content: "";
        position: absolute;
        top: 18px;
        left: 10px;
        background-color: @primary-color;
        height: 17px;
        width: 5px;
      }
    }
  }

  .curve-modal-body {
    padding: 14px;
    max-height: 700px;
    overflow: auto;
  }
  .curve-modal-footer {
    padding: 10px 16px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #e8e8e8;
    border-radius: 0 0 4px 4px;
    button {
      &:last-child {
        margin-left: 20px;
      }
    }
  }
  .ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 150px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
    }
  }
}
</style>
